package com.android.demo.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.android.demo.R;

public final class DrawView extends View {
	private Bitmap mBmp = null;
	private float mDistance = 0.0F;
	private boolean mIsStart = false;
	private long mLastTime;
	private Paint mTxtPaint;

	public DrawView(Context paramContext) {
		super(paramContext);
		long time = System.currentTimeMillis();
		mLastTime = time;
		init();
	}

	public DrawView(Context paramContext, AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
		long time = System.currentTimeMillis();
		mLastTime = time;
		init();
	}

	public void setStart(boolean paramBoolean) {
		mIsStart = paramBoolean;
		invalidate();
	}
	
	protected void init() {
		mTxtPaint = new Paint();

		// init bitmap
		mBmp = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_title_refresh);
		
//		float scale = 0.5f;
//		int w = (int)(mBmp.getWidth()*scale);
//		int h = (int)(mBmp.getHeight()*scale);
//		mBmp = Bitmap.createScaledBitmap(mBmp, w, h, false);
				
		if (getLayoutParams() != null) {
			getLayoutParams().height = mBmp.getHeight();
			getLayoutParams().width = mBmp.getWidth();
		}
		setStart(true);
	}

	protected void onDraw(Canvas paramCanvas) {
		// get distance
		long currentTime = System.currentTimeMillis();
		long lastTime = mLastTime;
		mDistance += (currentTime - lastTime);
		
		rotateView(paramCanvas);
		mLastTime = currentTime;
		
		// playing
		if (mIsStart) {
			invalidate();
		}
	}
	
	private void rotateView(Canvas paramCanvas){
//		int degree = ((int)(mDistance/3/45))*45;
		int degree = (int)(mDistance/3);
		paramCanvas.rotate(degree, mBmp.getWidth()/2,mBmp.getHeight()/2);
		paramCanvas.drawBitmap(mBmp, 0, 0, mTxtPaint);
	}
}